#pragma once 

#include <iostream>
#include <sys/epoll.h>
#include "Log.hpp"
#include "Commn.hpp"

namespace EpollerModule
{
    using namespace LogModule;
    class epoller 
    {
    public:
        epoller()
            :_epfd(-1)
        {}
        void Init()
        {
            _epfd = ::epoll_create(256);
            if (_epfd < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_create error";
                Die(EPOLL_CREATE_ERR);
            }
            LOG(LogLevel::INFO) << "epoll_create success: " << _epfd;
        }
        int Wait(epoll_event* revents,int maxval)
        {
            LOG(LogLevel::DEBUG) << "epoll_wait begin...";
            int n = ::epoll_wait(_epfd,revents,maxval,-1);
            if (n < 0)
            {
                LOG(LogLevel::WARNING) << "epoll_wait error";
                return -1;
            }
            return n;
        }
        void Delete(int sockfd)
        {
            int n = ::epoll_ctl(_epfd,EPOLL_CTL_DEL,sockfd,nullptr);
            if (n < 0)
            {
                LOG(LogLevel::WARNING) << "epoll_ctl error";
            }
        }
        void CTL(int sockfd,uint32_t events,int flg)
        {
            struct epoll_event ev;
            ev.events = events;
            ev.data.fd = sockfd;
            int n = ::epoll_ctl(_epfd,flg,sockfd,&ev);
            if (n < 0)
            {
                LOG(LogLevel::WARNING) << "epoll_ctl error";
            }
        }
        void Add(int sockfd,uint32_t events)
        {
            CTL(sockfd,events,EPOLL_CTL_ADD);
        }
        void Update(int sockfd,uint32_t events)
        {
            CTL(sockfd,events,EPOLL_CTL_MOD);
        }
        ~epoller(){}
    private:
        int _epfd;
    };
}

